package com.fsh.http.request;

import java.io.OutputStream ;
import java.io.UnsupportedEncodingException ;
import java.net.URLEncoder ;

import com.fsh.http.exception.HttpException ;
import com.fsh.http.util.Constant ;
import com.fsh.http.util.Util ;

/**
 * 封装Post请求的类
 * Description:	
 * @author 80002165
 * @date 2017年1月17日 下午3:25:30
 */
public class Post extends Request<Post>{
    private final byte[] params ;
    public Post(String url, int connectTimeout, int readTimeout, byte[] params) {
        super(url, connectTimeout, readTimeout) ;
        this.params = params ;
    }

    @Override
    protected Post doConnect() {
        defDoInputOrOutput();
        OutputStream os = null ;
        try {
            this.connection.setRequestMethod(Constant.HTTP_METHOD_POST);
            if(params != null && params.length>0){
                os = this.connection.getOutputStream();
                os.write(params);
                os.flush();
            }
            return this;
        } catch (Exception e) {
            throw new HttpException("Failed url：" + this.url, e) ;
        } finally{
            Util.quietlyCloseStream(os);
        }
    }
    
    /**
     * 
     * @author 80002165
     * @date 2017年1月17日 下午5:24:21
     * @param encoding 参数编码，默认UTF-8
     */
    public void setRequestProperty(String name, String value){
        setRequestProperty(name, value, Constant.DEF_ENCODING);
    }
    public void setRequestProperty(String name, String value, String encoding){
        if(Util.isEmpty(encoding)) encoding = Constant.DEF_ENCODING ;
        try {
            value = URLEncoder.encode(value, encoding);
        } catch (UnsupportedEncodingException e) {
            ;
        }   
        this.connection.setRequestProperty(name, value);   
    }
    
}
